# coding=utf-8
import struct

from bluepy.btle import DefaultDelegate, UUID, Peripheral


class HandlerDelegate(DefaultDelegate):
    # Constructor (run once on startup)
    def __init__(self):
        DefaultDelegate.__init__(self)

    # func is caled on notifications
    def handleNotification(self, cHandle, data):
        print("A notification was received: %s" % data)
        # print ("Notification from Handle: 0x" + format(cHandle, '02X') + " Value: " + format(ord(data[0])))


mac = "DC:A6:32:18:F5:D5"
# Initialisation  -------
service_uuid = UUID("13333333-3333-3333-3333-333333333001")
char_uuid = UUID("13333333-3333-3333-3333-333333333002")

if __name__ == "__main__":
    # if len(sys.argv) != 2:
    #     print "Fatal, must pass device address:", sys.argv[0], "<device address="">"
    #     quit()
    p = Peripheral(mac, "public")
    p.setDelegate(HandlerDelegate())
    service = p.getServiceByUUID(service_uuid)
    character = service.getCharacteristics(char_uuid)[0]
    hnd = character.getHandle()
    # Search and get Get The Button-Characteristics "property" (UUID-0x2902 CCC-Client Characteristic Configuration))
    #  wich is located in a handle in the range defined by the boundries of the ButtonService
    # for desriptor in p.getDescriptors(hnd, 0x00F):  # The handle range should be read from the services
    #     if (desriptor.uuid == 0x2902):  # but is not done due to a Bluez/BluePy bug :(
    #         print ("Button1 Client Characteristic Configuration found at handle 0x" + format(desriptor.handle, "02X"))
    #         hButtonCCC = desriptor.handle

    # Turn notifications on by setting bit0 in the CCC more info on:
    # https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
    p.writeCharacteristic(hnd + 1, struct.pack('<bb', 0x01, 0x00))
    print "Notification is turned on for Button1"
    # Main loop --------
    while True:
        if p.waitForNotifications(3.0):
            continue

        print "Waiting... Waited more than one sec for notification"
